package com.sgb.kjwl.view.ui.activity.manage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebsiteUpdataRyryReleaseBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.manage.AddItemEntity;
import com.sgb.kjwl.model.entity.manage.GloryHonorAdminEntity;
import com.sgb.kjwl.view.ui.adapter.manage.AddViewAdapter;
import com.sgb.kjwl.view.widget.SelectAlbumPopWindow;
import com.sgb.kjwl.viewmodel.manage.WebsiteUpDataRongYuRongYaoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * @author 张驰
 * @date 2021/5/13 17:15
 * @Description 网站发布，荣誉荣耀发布功能界面
 * @name com.sgb.kjwl.view.ui.activity.manage
 */
public class WebsiteUpDataRongYuRongYaoActivity extends WebSiteBuildBaseActivity {

    @Inject
    WebsiteUpDataRongYuRongYaoModel viewModel;
    private ActivityWebsiteUpdataRyryReleaseBinding binding;

    private String companyNo = ""; //编辑时，编辑编号
    private int siteType = 1; //网站类型  0-个人 1-企业 2-团队 默认为1
    private String title = ""; // 当前编辑的类型
    private boolean isInItView = true;
    //相册选择弹窗
    SelectAlbumPopWindow selectAlbumPopWindow;
    List<LocalMedia> selectionMedia = new ArrayList<>();
    PickSelectEntity<List<PickSelectEntity>> listPickSelectEntity;
    private int fidleType; //当前点击的是第一级还是第二级 0 第一级，1第二级
    private AddViewAdapter mAddViewAdapter;
    /**
     * @param context
     * @param id      网站编号
     */
    public static void start(Context context, String modelTitle, String id) {
        //网站类型  0-个人 1-企业 2-团队 默认为1
        int siteType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1);
        start(context, modelTitle, id, siteType);
    }

    /**
     * 企业网店 知识产权发布功能界面
     *
     * @param context   //     * @param modelTitle 名称
     * @param companyNo 编号
     * @param siteType  网站类型  0-个人 1-企业 2-团队 默认为1
     */
    public static void start(Context context, String modelTitle, String companyNo, int siteType) {
        Intent intent = new Intent(context, WebsiteUpDataRongYuRongYaoActivity.class);
        intent.putExtra("ModelTitle", modelTitle);
        intent.putExtra("companyNo", companyNo);
//        intent.putExtra("siteNo",siteNo);
        intent.putExtra("siteType", siteType);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).
                enterpriseManageModule(new EnterpriseManageModule(this)).
                build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(WebsiteUpDataRongYuRongYaoActivity.this, R.layout.activity_website_updata_ryry_release);
        binding.setViewModel(viewModel);
        title = getIntent().getStringExtra("ModelTitle");
        binding.include.titleView.setText(title + "发布");
        binding.include.ivBack.setOnClickListener(this);
        binding.tvCompanyType.setOnClickListener(this);
        binding.tvFidleType.setOnClickListener(this);
        binding.llTwo.setOnClickListener(this);
        binding.tvTime.setOnClickListener(this);
        binding.tvUpdate.setOnClickListener(this);
        binding.ivUpdataImage.setOnClickListener(this);
        binding.ivDelect.setOnClickListener(this);
        companyNo = getIntent().getStringExtra("companyNo");
        siteType = getIntent().getIntExtra("siteType", 1);
        binding.etName.setHint(String.format(getResources().getString(R.string.swk_input_hint), title));
        mAddViewAdapter = new AddViewAdapter(this);
        binding.addView.setAdapter(mAddViewAdapter);
        initDataBack();
    }

    private void initDataBack() {
        viewModel.getMessage().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (!TextUtils.isEmpty(s)) {
                    if ("数据回显".equals(s)) {
                        setView(viewModel.getMutableLiveData().getValue());
                    } else {
                        MToast.showToast(getActivity(), s);
                        finish();
                        return;
                    }
                }
            }
        });
        viewModel.getMutableLiveData().observe(this, new Observer<GloryHonorAdminEntity>() {
            @Override
            public void onChanged(GloryHonorAdminEntity gloryHonorAdminEntity) {
                setUpdateData(gloryHonorAdminEntity);
                if (gloryHonorAdminEntity.getCustomFieldList() != null) {
                    binding.addView.setData(gloryHonorAdminEntity.getCustomFieldList());
                }
            }
        });
        viewModel.getHonorPickSelectList().observe(this, new Observer<List<PickSelectEntity<List<PickSelectEntity>>>>() {
            @Override
            public void onChanged(List<PickSelectEntity<List<PickSelectEntity>>> pickSelectEntityList) {
                if (isInItView) return;
                if (pickSelectEntityList.size() == 0) {
                    MToast.showToast(getActivity(), "暂无数据");
                    return;
                }
                if (fidleType == 0){
                    List<PickSelectEntity> pickSelectEntities = new ArrayList<>();
                    pickSelectEntities.addAll(pickSelectEntityList);
                    showOnlyTypeWin(pickSelectEntities, "荣耀", "请选择荣耀分类");
                }
            }
        });
        viewModel.getTypePickSelectList().observe(this, new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> pickSelectEntityList) {
                if (isInItView) return;
                if (pickSelectEntityList.size() == 0) {
                    MToast.showToast(getActivity(), "暂无数据");
                    return;
                }
                showOnlyTypeWin(pickSelectEntityList, "行业", "请选择行业分类");
            }
        });
        viewModel.getUrlString().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                showAvatar(s);
            }
        });
    }

    private void setUpdateData(GloryHonorAdminEntity gloryHonorAdminEntity) {
        binding.setData(gloryHonorAdminEntity);
        if (isInItView){
            if (!TextUtils.isEmpty(gloryHonorAdminEntity.getHonorLevelTwoName())){
                binding.llTwo.setVisibility(View.VISIBLE);
            }else{
                binding.llTwo.setVisibility(View.GONE);
            }
        }
    }

    private void setView(GloryHonorAdminEntity gloryHonorAdminEntity) {
        for (PickSelectEntity<List<PickSelectEntity>> pickSelectEntity : viewModel.getHonorPickSelectList().getValue()) {
            if (pickSelectEntity.getProjectscale().equals(gloryHonorAdminEntity.getHonorClassificationName())) {
                listPickSelectEntity = pickSelectEntity;
                if (listPickSelectEntity == null || listPickSelectEntity.getChildren() == null || listPickSelectEntity.getChildren().size() == 0) {
                }else{
                    if (listPickSelectEntity != null && listPickSelectEntity.getChildren() != null){
                        showOnlyTypeWin(listPickSelectEntity.getChildren(), "二级荣耀", "请选择荣耀类型");
                    }
                }
            }
        }
    }

    @Override
    protected void init() {
        if (!TextUtils.isEmpty(companyNo)) {
            viewModel.getGloryHonorAdminDetailById(getActivity(), companyNo);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_update:
                if (!ClickUtils.isDoubleClick()) {
                    Map<String, Object> map = saveOrUpData();
                    if (map == null) return;
                    viewModel.gloryHonorAdminsaveOrUpdate(getActivity(), map);
                }
                break;
            case R.id.tv_companyType:  //行业分类
                isInItView = false;
                if (viewModel.getTypePickSelectList().getValue().size() == 0) {
                    viewModel.getAllCategory(getActivity(), title);
                } else {
                    showOnlyTypeWin(viewModel.getTypePickSelectList().getValue(), "行业", "请选择行业分类");
                }
                break;
            case R.id.tv_fidleType:  //荣耀分类
                isInItView = false;
                fidleType = 0;
                if (viewModel.getHonorPickSelectList().getValue().size() == 0) {
                    viewModel.getHonorlist(getActivity(), "");
                } else {
                    List<PickSelectEntity> pickSelectEntities = new ArrayList<>();
                    pickSelectEntities.addAll(viewModel.getHonorPickSelectList().getValue());
                    showOnlyTypeWin(pickSelectEntities, "荣耀", "请选择荣耀分类");
                }
                break;
            case R.id.ll_two:  //荣耀二级分类
                isInItView = false;
                fidleType = 1;
                if (listPickSelectEntity == null || listPickSelectEntity.getChildren() == null || listPickSelectEntity.getChildren().size() == 0) {
                    viewModel.getHonorlist(getActivity(), "数据回显");
                } else {
                    showOnlyTypeWin(listPickSelectEntity.getChildren(), "二级荣耀", "请选择二级荣耀分类");
                }
                break;
            case R.id.iv_updata_image: //图片上传
                isInItView = false;
                if (selectAlbumPopWindow == null) {
                    initAlbumPop();
                }
                showAlbumPop();
                break;
            case R.id.iv_delect: //清空图片
                isInItView = false;
                showAvatar("");
                break;
            case R.id.tv_time: //时间选择
                isInItView = false;
                Date date = null;
                if (0 != viewModel.getMutableLiveData().getValue().getDateOfIssue()) {
                    date = DateUtils.getCustomizeDayNight(0, viewModel.getMutableLiveData().getValue().getDateOfIssue());
                }
                showCourseTimePop(date);
                break;
        }
    }

    private Map<String, Object> saveOrUpData() {
        Map<String, Object> map = new HashMap<>();
        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getHonorName())) {
            MToast.showToast(getActivity(), "请输入" + title + "名称");
            return null;
        }
        map.put("honorName", viewModel.getMutableLiveData().getValue().getHonorName());//荣誉名称

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getIndustryTypeNo())) {
            MToast.showToast(getActivity(), "请选择行业分类");
            return null;
        }
        map.put("industryTypeNo", viewModel.getMutableLiveData().getValue().getIndustryTypeNo());//行业类型No

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getHonorClassification())) {
            MToast.showToast(getActivity(), "请选择荣誉分类");
            return null;
        }
        map.put("honorTypeNo", viewModel.getMutableLiveData().getValue().getHonorClassification());//荣誉分类NO
        map.put("honorClassification", viewModel.getMutableLiveData().getValue().getHonorClassification());//荣誉分类NO
        map.put("honorClassificationName", viewModel.getMutableLiveData().getValue().getHonorClassificationName());//荣誉分类NO

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getHonorLevelTwoName()) && listPickSelectEntity != null && listPickSelectEntity.getChildren()!= null && listPickSelectEntity.getChildren().size() != 0) {
            MToast.showToast(getActivity(), "请选择荣誉类型");
            return null;
        }
        map.put("honorLevelTwoName", viewModel.getMutableLiveData().getValue().getHonorLevelTwoName());
        map.put("honorLevelTwoNo", viewModel.getMutableLiveData().getValue().getHonorLevelTwoNo());

        if (0 == viewModel.getMutableLiveData().getValue().getDateOfIssue()) {
            MToast.showToast(getActivity(), "请选择颁发时间");
            return null;
        }
        map.put("dateOfIssue", viewModel.getMutableLiveData().getValue().getDateOfIssue());//颁发日期

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getHonorPictures())) {
            MToast.showToast(getActivity(), "请上传照片");
            return null;
        }
        map.put("honorPictures", viewModel.getMutableLiveData().getValue().getHonorPictures());//图片上传
        map.put("siteType", siteType + "");//网站类型  0-个人 1-企业 2-团队

        if (!TextUtils.isEmpty(companyNo)) {
            map.put("id", companyNo);
        }
        List<AddItemEntity> list = binding.addView.getDate();
           // map.put("customFields", list);
        map.put("customFieldList", list);

        map.put("no", viewModel.getMutableLiveData().getValue().getNo());
        return map;
    }

    //时间选择
    private void showCourseTimePop(Date selectDate) {
//        Calendar dayCalendar = Calendar.getInstance();
//        if (selectDate == null){
//            dayCalendar.setTime(new Date());
//        }else{
//            dayCalendar.setTime(selectDate);
//        }
//        dayCalendar.add(Calendar.DAY_OF_MONTH, 1);

        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                viewModel.getMutableLiveData().getValue().setDateOfIssue(date.getTime());
                setUpdateData(viewModel.getMutableLiveData().getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setTitleText("请选择颁发时间")
                .setTitleColor(getResources().getColor(R.color.color_tab_three)).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main))
//                .setRangDate(dayCalendar, null)
                .build();
        timePicker.show();
    }

    //单层选择
    private void showOnlyTypeWin(List<PickSelectEntity> selectedDate, String type, String name) {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = selectedDate.get(options1).getProjectscale();
            String no = selectedDate.get(options1).getNo();
            switch (type) {
                case "行业":
                    viewModel.getMutableLiveData().getValue().setIndustryTypeName(content);
                    viewModel.getMutableLiveData().getValue().setIndustryTypeNo(no);
                    break;
                case "荣耀":
                    listPickSelectEntity = selectedDate.get(options1);
                    if (listPickSelectEntity != null && listPickSelectEntity.getChildren() != null && listPickSelectEntity.getChildren().size() != 0){
                        binding.llTwo.setVisibility(View.VISIBLE);
                    }else{
                        viewModel.getMutableLiveData().getValue().setHonorLevelTwoName("");
                        viewModel.getMutableLiveData().getValue().setHonorLevelTwoNo("");
                        binding.llTwo.setVisibility(View.GONE);
                    }
                    viewModel.getMutableLiveData().getValue().setHonorClassificationName(content);
                    viewModel.getMutableLiveData().getValue().setHonorClassification(no);
                    break;
                case "二级荣耀":
                    viewModel.getMutableLiveData().getValue().setHonorLevelTwoName(content);
                    viewModel.getMutableLiveData().getValue().setHonorLevelTwoNo(no);
                    break;
            }
            //viewModel.getMutableLiveData().postValue(viewModel.getMutableLiveData().getValue());
            setUpdateData(viewModel.getMutableLiveData().getValue());
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setTitleText(name)
                .setTitleColor(getResources().getColor(R.color.color_tab_three)).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main))
                .build();
        businessOption.setPicker(selectedDate);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //展开popuwindw
    private void showAlbumPop() {
        //判断是否在未展示的情况
        if (!selectAlbumPopWindow.isShowing()) {
            //满足条件展示
            selectAlbumPopWindow.showDownPopwindow(binding.grayLayout, true);
        }
    }

    private void initAlbumPop() {
        if (selectAlbumPopWindow == null) {
            //满足条件，创建SelectAlbumPopWindow
            selectAlbumPopWindow = new SelectAlbumPopWindow(this);
        }
        //设置背景
        selectAlbumPopWindow.setBgView(binding.grayLayout);
        //设置点击回调
        selectAlbumPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int type = (int) key1;
                if (type == 0) {
                    pictureSelector(true, 500, 1);
                    selectAlbumPopWindow.dismiss();
                }
            }
        });
    }

    private void showAvatar(String avatar) {
        viewModel.getMutableLiveData().getValue().setHonorPictures(avatar);
        if (TextUtils.isEmpty(avatar)) {
            binding.ivDelect.setVisibility(View.GONE);
            binding.ivUpdataImage.setImageResource(R.drawable.sck);
        } else {
            binding.ivDelect.setVisibility(View.VISIBLE);
            //Glide展示图片
            Glide.with(this)
                    //加载设置宽高限制
                    .load(avatar + "?x-oss-process=image/resize,m_fixed,h_100")
                    //显示圆图
//                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    //设置为头像
                    .into(binding.ivUpdataImage);
        }
    }

    //结果回调
    @Override
    protected void onPictureSelectorResult(List<LocalMedia> selectList) {
        // 获取到图片的本地路径
        String path = selectList.get(0).getCompressPath();
        //保存在文件中
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            //接口上传文件
            viewModel.uploadAvatar(getActivity(), file);
            //上传时，出现上传弹窗
            DialogHelper.showProgressDialog(this, null, "头像上传中...", 0, false, null).setCanceledOnTouchOutside(false);
        } else {
            MToast.showToast(getApplicationContext(), "获取图片失败！");
        }
    }
}
